package com.linkage.jz.bankruptcy.activity.Project;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.linkage.jz.bankruptcy.BankruptcyApp;
import com.linkage.jz.bankruptcy.Consts;
import com.linkage.jz.bankruptcy.R;
import com.linkage.jz.bankruptcy.activity.Guide.GuideActivity;
import com.linkage.jz.bankruptcy.activity.MainActivity;
import com.linkage.jz.bankruptcy.activity.Project.ZQUser.CreateZQOneProjectActivity;
import com.linkage.jz.bankruptcy.activity.Project.ZQUser.ZQUserZQDetailActivity;
import com.linkage.jz.bankruptcy.base.BaseActivity;
import com.linkage.jz.bankruptcy.bean.ContactInfo;
import com.linkage.jz.bankruptcy.bean.LoginInfo;
import com.linkage.jz.bankruptcy.bean.TokenInfo;
import com.linkage.jz.bankruptcy.bean.ZQUserDetailBaseInfo;
import com.linkage.jz.bankruptcy.net.BaseSubscriber;
import com.linkage.jz.bankruptcy.net.Network;
import com.linkage.jz.bankruptcy.net.ToastUtil;
import com.linkage.jz.bankruptcy.utils.SPUtils;
import com.linkage.jz.bankruptcy.utils.SignUtil;
import com.linkage.jz.bankruptcy.utils.Utils;
import com.linkage.jz.bankruptcy.widget.CreateZQUserNoticeDialog;
import com.linkage.jz.bankruptcy.widget.PublicLoginNoticeDialog;
import com.linkage.jz.bankruptcy.widget.PublicLongNoticeDialog;
import com.linkage.jz.bankruptcy.widget.ShapeLoadingDialog;
import com.linkage.seapeak.activity.register.RegisterActivity;
import com.linkage.seapeak.view.QuickPopView;
import com.linkage.seapeak.view.QuickUserPopView;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.IOException;
import java.util.HashMap;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;


//import butterknife.Bind;
//import butterknife.ButterKnife;

/**
 * 欢迎页
 */
public class ApplyProNoticeActivity extends BaseActivity implements OnClickListener {
    private static final String TAG = ApplyProNoticeActivity.class.getSimpleName();

    ImageView ivWelcome;
    Button btn_commit,btn_change;
    ImageView iconWelcomeIv;
    RelativeLayout bottomImg;
    private ShapeLoadingDialog shapeLoadingDialog;


    boolean flag = true;
    private  static  String mProId;
    private static String mCId;

    private TextView popClick;
    private static String mUserid;
    private static String mUsername;
    private static String mPhone;
    View top_back;

    public static void start(Context context,String proId,String cId,String userid,String username,String phone) {
        Intent intent = new Intent(context, ApplyProNoticeActivity.class);
        context.startActivity(intent);
        mProId = proId;
        mCId = cId;
        mUserid = userid;
        mUsername = username;
        mPhone = phone;
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        //全屏
        getWindow().setFlags(WindowManager.LayoutParams. FLAG_FULLSCREEN ,
                WindowManager.LayoutParams. FLAG_FULLSCREEN);

        setContentView(R.layout.activity_apply_pro_notice);

        String noticeStr = "为了保障债权人的合法权益，加入前请再次确认您是相关债权人本人或法定代表人，或是其代理人，并将以本手机号码"
                + BankruptcyApp.loginInfo.getLoginname() + "注册的账户代表相关债权人进行操作，如须变更号码线上操作，请点击变更操作用户，填写操作人的手机号。您也可联系管理人，由管理人协助操作用户加入。";

        ((TextView) findViewById(R.id.iv_welcome)).setText(noticeStr);
        btn_commit = findViewById(R.id. btn_commit);
                btn_change = findViewById(R.id.btn_change);
        shapeLoadingDialog = new ShapeLoadingDialog(this);
        top_back = findViewById(R.id.top_back);
        top_back.setOnClickListener(this);
        super.onCreate(savedInstanceState);
    }

    @Override
    public void initData() {

    }

    @Override
    public void initTitle() {
        TextView top_title = findViewById(R.id.top_title);
        top_title.setText("重要须知");
    }

    @Override
    public void initView() {
        popClick = findViewById(R.id.pop_click);
        /**
         * 弹窗
         */
        popClick.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //等参数
                getProjetContact();
//                QuickUserPopView.show(ApplyProNoticeActivity.this,mUserid,mProId,mUsername,mPhone);
            }
        });
    }

    @Override
    public void setListener() {
        btn_commit.setOnClickListener(this);
        btn_change.setOnClickListener(this);
    }

    private PublicLongNoticeDialog noticelxDialog;

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_change:
                ChangerUserActivity.start(this,mProId);
                finish();
                break;
            case R.id.top_back:
                finish();
                break;
            case R.id.btn_commit:

                noticelxDialog = new PublicLongNoticeDialog(ApplyProNoticeActivity.this, new View.OnClickListener() {
                    @Override
                    public void onClick( View view ) {

                        if (view.getId() == R.id.btn_save_notice_lx) {//暂存

                            if(!noticelxDialog.cb_agree.isChecked())
                            {
                                ToastUtil.showShort("请先同意项目规则");
                                return;
                            }
                            accpectOrRefData(mProId, "1");
                        } else if (view.getId() == R.id.ll_close) {
                            noticelxDialog.dismiss();
                            return;
                        } else {//生成

                        }
                        noticelxDialog.dismiss();

                    }
                }, 1, "提示", "", "取消", "确定");
                noticelxDialog.show();
                break;
            default:
                break;
        }
    }

    public void accpectOrRefData(String msgId, String type) {
        shapeLoadingDialog.setLoadingText("加载中...");
        shapeLoadingDialog.setCanceledOnTouchOutside(false);
        shapeLoadingDialog.show();
        OkHttpClient okHttpClient = new OkHttpClient();
        Random random = new Random();
        String rom = random.nextLong() + "";
        String timestamp = System.currentTimeMillis() + "";
        String userToken = SPUtils.getInstance(Consts.SPNAME).getString("userToken", "");

        if ("".equalsIgnoreCase(userToken)) {
            return;
        }
        RequestBody requestBody = new FormBody.Builder()
                .add("appid", "1000000001")
                .add("nonce", rom)
                .add("timestamp", timestamp)
                .add("token", BankruptcyApp.tokeninfo.getToken())
                .add("userToken", userToken)
                .add("projectId", msgId)
                .add("opType", type)
                .build();

        String url = Consts.WEBURL_ACCORREF;
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
//                Log.d(TAG, "onFailure: " + e.getMessage());
                shapeLoadingDialog.dismiss();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
//                Log.d(TAG, response.protocol() + " " +response.code() + " " + response.message());
                Headers headers = response.headers();
                shapeLoadingDialog.dismiss();


                String str = response.body().string();
                try {
                    final JSONObject object = new JSONObject(str);
                    if (object.optInt("code") == 0) {
//
//                        Toast.makeText(PhoneLoginActivity.this,"请求成功，请查看短信"+object.optString("data"),Toast.LENGTH_SHORT).show();
                       runOnUiThread(new Runnable() {

                            @Override
                            public void run() {


//                                Toast.makeText(ApplyProNoticeActivity.this, "请求成功", Toast.LENGTH_SHORT).show();
                                ZQUserDetailBaseInfo info = new ZQUserDetailBaseInfo();
                                info.setBankruptcyProjectId(mProId);
                                info.setId(mCId);
                                CreateZQOneProjectActivity.start(ApplyProNoticeActivity.this,info,mUserid,mUsername,mPhone);
                                finish();
                            }

                        });

                    } else {
                        runOnUiThread(new Runnable() {

                            @Override
                            public void run() {

                                Toast.makeText(ApplyProNoticeActivity.this, "加入失败:" + object.optString("msg"), Toast.LENGTH_SHORT).show();
                            }

                        });
                    }


                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        });
    }


    public void getProjetContact() {

        Observable<JsonObject> observable;

        observable = Network
                .getAPIService()
                .getProjetContact(getUserToken(),mProId);


        observable
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<JsonObject>() {
                    @Override
                    public void onNext(JsonObject json) {

                        int code = json.get("code").getAsInt();

                        if(code == 0)
                        {
                            ContactInfo info = new Gson().fromJson(json.getAsJsonObject("data"),ContactInfo.class);
                            if(info!=null)
                            QuickUserPopView.show(ApplyProNoticeActivity.this,info.getSysUserId(),mProId,info.getName(),info.getMobile());
                        }else
                        {
                            ToastUtil.showShort(json.get("msg").getAsString());

                        }
                    }

                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                    }

                    @Override
                    public void onError(Throwable e) {

                        super.onError(e);
                    }
                });
    }
}
